import global from 'common/globals'

export function doMathId(matchedItemObj, menuData, currentPath) {
  menuData.forEach(item => {
    if (item.menuUrl === currentPath) {
      matchedItemObj.push(item, item.id)
    } else if (item.children && item.children.length > 0) {
      doMathId(matchedItemObj, item.children, currentPath)
    }
  })
}

function queryBreadChain(menuId, matchedParentItms, menuData) {
  menuData.forEach(item => {
    if (item.id === menuId) {
      matchedParentItms.push(item)
    } else if (item.children && item.children.length >= 0) {
      queryBreadChain(menuId, matchedParentItms, item.children)
    }
  })
}

export function matchBreadData(currentPath, menuData) {
  let matchedData = []
  const matchedItemObj = []

  if (!menuData || menuData.length === 0) {
    return matchedData
  }

  doMathId(matchedItemObj, menuData, currentPath)

  if (matchedItemObj.length <= 1) {
    return matchedData
  }

  const parentId = matchedItemObj[0]['parentId']
  matchedData.push(matchedItemObj[0])

  if (!parentId || parentId === '0') {
    return matchedData
  } else {
    const parentIds = matchedItemObj[0]['parentIds'].split(',').slice(1).reverse()
    const matchedParentItms = []
    parentIds.forEach(id => {
      queryBreadChain(id, matchedParentItms, menuData)
    })
    matchedData = matchedData.concat(matchedParentItms)
  }

  return matchedData.reverse()
}

function queryParentMenu(parentPath, routes, arr = []) {
  const parentItem = routes.find(item => item.path === parentPath)
  if (parentItem) {
    arr.push(parentItem)
    if (parentItem.meta.parentPath) {
      queryParentMenu(parentItem.meta.parentPath, routes, arr)
    }
  }
  return arr
}
export function addNotMatchedBreadData(currentRoute, routes, breadData) {
  const arr = []
  if (currentRoute && currentRoute.meta.parentPath) {
    queryParentMenu(currentRoute.meta.parentPath, routes, arr)
  }
  for (let i = arr.length - 1; i >= 0; i -= 1) {
    const item = arr[i]
    let menuUrlTmp = item.path
    if (global.store.state.pageStatusInfo[item.name]) {
      menuUrlTmp = global.store.state.pageStatusInfo[item.name]
    }
    breadData.push({
      id: `not-matched-${item.name}`,
      menuUrl: menuUrlTmp,
      menuName: item.meta.title,
      hasChildren: false,
    })
  }
}
